<template>
  <div style="min-height: 370px">
    <a-form ref="roleForm" :model="entity" :rules="rules" label-width="120px"  @submit.native.prevent>
      <a-form-item label="角色名称" field="roleName">
        <a-input v-model="entity.roleName" @keyup.enter.native="btnSubmit" ref="roleName" placeholder="角色名称" />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="btnSubmit">确 定</a-button>
          <a-button type="primary" @click="onCancel">取 消</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { Message } from '@arco-design/web-vue'
import mittBus from "@/utils/route-listener"
import {reactive, ref, onMounted, defineProps, defineEmits, nextTick} from "vue";

// 定义变量内容
const roleForm = ref(null);
const roleName = ref(null);
const emit = defineEmits(['update:modelValue'])
let props = defineProps({
  modelValue : {type : Boolean, default: true},
  entityId : {type : Number, default: 0}
})
let entity = ref({
  roleName: '',
})
const rules = reactive( {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { minLength: 2, maxLength: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
})

const loadEntity = ()=>{
  if(props.entityId > 0){
    axios.post('/sys/role/getrole', {id : props.entityId} ).then( res =>{
      entity.value = res.data
    })
  }
}
const onCancel = ()=>{
  emit('update:modelValue', false) //关闭弹窗
}
const btnSubmit = async()=>{
  if(!roleForm.value) return;
  roleForm.value.validate().then((errors) =>{
    if(!errors){  //如果没有错误
      axios.post('/sys/role/addeditrole', entity.value).then( res =>{
        const {code,msg} = res;
        if (code !== "200") {
          Message.error(msg);
        } else {
          Message.success(msg)
          emit('update:modelValue', false) //关闭弹窗
          props.entityId > 0 ? mittBus.emit('roleedit', {}) : mittBus.emit('roleadd', {}); //触发事件总线，让列表界面更新数据
        }
      })
    }
  })
}
onMounted(() => {
  loadEntity();
  nextTick(()=>{
    roleName.value.focus()
  })
});
</script>

<style scoped>

</style>
